package com.molyfun.parents.activity;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseUI;
import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.account.LoginActivity;
import com.molyfun.parents.activity.common.BaseActivity;
import com.molyfun.parents.activity.organization.OrganizationActivity;
import com.molyfun.parents.dao.entity.SingleChatDB;
import com.molyfun.parents.dao.gen.DaoMaster;
import com.molyfun.parents.dao.gen.DaoSession;
import com.molyfun.parents.dao.gen.SingleChatDBDao;
import com.molyfun.parents.fragment.dialog.MUpDateDialogFragment;
import com.molyfun.parents.fragment.dialog.MainActivityListDialogFragment;
import com.molyfun.parents.im.MyConnectionListener;
import com.molyfun.parents.im.MyTIMMsgListener;
import com.molyfun.parents.im.model.BaseMessageEntity;
import com.molyfun.parents.im.model.ChatMessageEntity;
import com.molyfun.parents.rest.bean.CheckVersionResponse;
import com.molyfun.parents.rest.bean.MainActivityListResponse;
import com.molyfun.parents.service.DownloadApkService;
import com.molyfun.parents.uievent.EventDispatcherEnum;
import com.molyfun.parents.uievent.UIEventListener;
import com.molyfun.parents.utils.AndroidBug5497Workaround;
import com.molyfun.parents.utils.BadgeUtil;
import com.molyfun.parents.utils.Const;
import com.molyfun.parents.utils.GsonUtil;
import com.molyfun.parents.utils.LogUtils;
import com.molyfun.parents.utils.LoginTIMUtil;
import com.molyfun.parents.utils.PreferencesStorageUtil;
import com.molyfun.parents.utils.UIUtils;
import com.molyfun.parents.view.MainPagerAdapter;
import com.molyfun.parents.view.ZNViewPager;
import com.tencent.imsdk.TIMManager;
import com.tencent.imsdk.TIMOfflinePushSettings;
import com.xiaomi.channel.commonutils.logger.LoggerInterface;
import com.xiaomi.mipush.sdk.Logger;
import com.xiaomi.mipush.sdk.MiPushClient;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends BaseActivity implements View.OnClickListener, EMMessageListener, UIEventListener, MyTIMMsgListener.ITIMMsgReceivedCallback {

    private static final String TAG = MainActivity.class.getSimpleName();
    private static final String TAGS = "MainActivity";

    public static final int REQUEST_CODE_CHANGE_ORGANIZATION = 2001;


    @InjectView(R.id.viewpager)
    ZNViewPager viewpager;

    @InjectView(R.id.rl_tab_mine_classroom)
    LinearLayout mTab1Layout;
    @InjectView(R.id.rl_tab_school_online)
    LinearLayout mTab2Layout;
    @InjectView(R.id.rl_tab_class_center)
    LinearLayout mTab3Layout;
    @InjectView(R.id.rl_tab_mine_msg)
    LinearLayout mTab4Layout;

    @InjectView(R.id.tab_img_class_center)
    ImageView mTabImgClassCenter;
    @InjectView(R.id.tab_img_school_online)
    ImageView mTabImgSchoolOnline;
    @InjectView(R.id.rl_tab_main)
    LinearLayout mTabMain;
    @InjectView(R.id.tab_img_mine_classroom)
    ImageView mTabImgMineClassroom;
    @InjectView(R.id.tab_img_mine_msg)
    ImageView mTabMineMsg;
    @InjectView(R.id.red_icon)
    ImageView mRedIcon;

    private MainPagerAdapter pagerAdapter;
    private int mCurrentTab;
    // 记录退出时间
    private long mExitTime;
    private MyConnectionListener myConnectionListener;
    private MyTIMMsgListener mMyTIMMsgListener;
    private SingleChatDBDao mSingleChatDBDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        AndroidBug5497Workaround.assistActivity(this);

        if (isMiuiSystem(this)) {
            MiPushClient.registerPush(this, "2882303761517534345", "5871753483345");
            LoggerInterface newLogger = new LoggerInterface() {
                @Override
                public void setTag(String tag) {
                    // ignore
                }

                @Override
                public void log(String content, Throwable t) {
                    Log.d("MIPush", content, t);
                }

                @Override
                public void log(String content) {
                    Log.d("MIPush", content);
                }
            };
            switch (PreferencesStorageUtil.getServerMode(MFPApplication.getInstance())) {
                case PreferencesStorageUtil.ServerMode.OFFICAL:
                    MiPushClient.setAlias(this, MFPApplication.getInstance().getUser().getId(), null);
                    break;
                case PreferencesStorageUtil.ServerMode.PREPARE:
                case PreferencesStorageUtil.ServerMode.TEST:
                    MiPushClient.setAlias(this, "test_" + MFPApplication.getInstance().getUser().getId(), null);
                    break;
            }

            Logger.setLogger(this, newLogger);
            if (!JPushInterface.isPushStopped(this)) {
                JPushInterface.stopPush(this);
            }

        } else {
            if (JPushInterface.isPushStopped(this)) {
                JPushInterface.resumePush(this);
            } else {
                JPushInterface.init(this);
            }
            if (MFPApplication.getInstance().getUser() != null) {
                switch (PreferencesStorageUtil.getServerMode(MFPApplication.getInstance())) {
                    case PreferencesStorageUtil.ServerMode.OFFICAL:
                        JPushInterface.setAlias(this, MFPApplication.getInstance().getUser().getId(), new TagSetCallback());
                        break;
                    case PreferencesStorageUtil.ServerMode.PREPARE:
                    case PreferencesStorageUtil.ServerMode.TEST:
                        JPushInterface.setAlias(this, "test_" + MFPApplication.getInstance().getUser().getId(), new TagSetCallback());
                        break;
                }
            }

        }

        getSupportActionBar().setTitle("");
        ButterKnife.inject(this);

        //展示弹窗
        getActivityList();

        checkVersion();

        initIntent(getIntent());
//        EMClient.getInstance().addConnectionListener(new MyConnectionListener(MainActivity.this));
//        EMClient.getInstance().chatManager().addMessageListener(this);
        myConnectionListener = new MyConnectionListener(this);
//        EMClient.getInstance().addConnectionListener(myConnectionListener);
//        isLogin();
        addTIMConfig();
        loginTIM();

        mTab1Layout.setOnClickListener(this);
        mTab2Layout.setOnClickListener(this);
        mTabMain.setOnClickListener(this);
        mTab3Layout.setOnClickListener(this);
        mTab4Layout.setOnClickListener(this);

        initViewPager();

        BadgeUtil.resetBadgeCount(this, R.mipmap.ic_launcher);
        MFPApplication.getInstance().getEventController().addUIEventListener(EventDispatcherEnum.UI_EVENT_CHANGE_TAB, this);
        MyTIMMsgListener.addITIMMsgReceivedCallback(this);

        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(MFPApplication.getInstance(), Const.DB_NAME, null);
        DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
        DaoSession daoSession = daoMaster.newSession();
        mSingleChatDBDao = daoSession.getSingleChatDBDao();

    }

    @Override
    public void handleUIEvent(Message msg) {

        System.out.println("MainActivity---handleUIEvent->");
        if (msg.what == EventDispatcherEnum.UI_EVENT_CHANGE_TAB) {
            int changePageId = msg.arg1;
            setCurrentPage(changePageId);
            System.out.println("MainActivity---handleUIEvent->UI_EVENT_CHANGE_TAB");
        }
    }

    public class TagSetCallback implements TagAliasCallback {

        @Override
        public void gotResult(int i, String s, Set<String> set) {
            System.out.println("i--->" + i + " s--->" + s);
        }
    }

    private void initViewPager() {
        viewpager.setScrollEnable(false);
        viewpager.setOffscreenPageLimit(5);
        pagerAdapter = new MainPagerAdapter(getSupportFragmentManager());
        viewpager.setAdapter(pagerAdapter);
        viewpager.setCurrentItem(2);
    }


    private void loginTIM() {
        LoginTIMUtil.getInstance().loginTIM(new LoginTIMUtil.ILoginTIMCallback() {
            @Override
            public void onSuccess() {
//                updateUnreadTIMMsgCount();
                setOfflinePush();
            }

            @Override
            public void onError() {
                myConnectionListener.showHint();
            }
        });
    }

    private void setOfflinePush() {
        TIMOfflinePushSettings pushSettings = new TIMOfflinePushSettings();
        pushSettings.setEnabled(true);
        pushSettings.setGroupMsgRemindSound(null);
        pushSettings.setC2cMsgRemindSound(null);
        TIMManager.getInstance().setOfflinePushSettings(pushSettings);
    }

    private void addTIMConfig() {
        myConnectionListener = new MyConnectionListener(this);
        TIMManager.getInstance().getUserConfig().setUserStatusListener(myConnectionListener);
        mMyTIMMsgListener = new MyTIMMsgListener();
        TIMManager.getInstance().addMessageListener(mMyTIMMsgListener);
    }

    @Override
    public void onMessage(BaseMessageEntity messageEntity) {
        switch (messageEntity.getEventtype()) {
            case MyTIMMsgListener.EventType.CUSTOMPLAN:
//                if (messageEntity.getOpertype().equals(MyTIMMsgListener.OperType.GROUPMSG)) {
//                    ChatMessageEntity chatMessageEntity = GsonUtil.fromJson(messageEntity.getData(), ChatMessageEntity.class);
//                    showNotification(chatMessageEntity);
//                }
                break;
            case MyTIMMsgListener.EventType.LOGIN:
                if (LoginTIMUtil.getInstance().isLogoutMyAccount() && messageEntity.getOpertype().equals(MyTIMMsgListener.OperType.IM_LOGINOUT)) {
                    PreferencesStorageUtil.logout(MFPApplication.getInstance());
                    Intent intent = new Intent(MFPApplication.getInstance(), LoginActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    MFPApplication.getInstance().startActivity(intent);
                    com.molyfun.parents.utils.ActivityManager.getInstance().logout();
                    UIUtils.showToast(MFPApplication.getInstance(), "您的账号已在其它设备登录");
                }
                break;
            case MyTIMMsgListener.EventType.IM_MSG:

                if(mCurrentTab != R.mipmap.main_tab_4_normal){
                    mRedIcon.setVisibility(View.VISIBLE);
                }
                ChatMessageEntity chatMessageEntity = GsonUtil.fromJson(messageEntity.getData(), ChatMessageEntity.class);
                SingleChatDB singleChatDB = mSingleChatDBDao.queryBuilder().where(SingleChatDBDao.Properties.Conversationid.eq(messageEntity.getConversationid())).build().unique();
                if (singleChatDB != null) {
                    int unreadCount = singleChatDB.getUnReadMsgCount();
                    if(!messageEntity.getUser().getUserid().equals(MFPApplication.getInstance().getUser().getId())){
                        singleChatDB.setUnReadMsgCount(unreadCount + 1);
                    }
                    singleChatDB.setLastMsgTime(chatMessageEntity.getMsgTime());
                    singleChatDB.setTxuserid(PreferencesStorageUtil.getIMUserName(this));
                    if (messageEntity.getOpertype().equals(MyTIMMsgListener.OperType.GROUPMSG)) {
                        //如果是群聊，要更新群聊人数
                        singleChatDB.setUserCount(messageEntity.getDetaildata().getCount());
                        singleChatDB.setName(messageEntity.getDetaildata().getName());
                        singleChatDB.setCover(messageEntity.getDetaildata().getUrl());
                        singleChatDB.setTeamMemberCount(messageEntity.getDetaildata().getCount());
                        singleChatDB.setTeamId(messageEntity.getDetaildata().getId());
                        singleChatDB.setType(messageEntity.getDetaildata().getType());
                        singleChatDB.setTeamLiveState(messageEntity.getDetaildata().getStatus());
                        singleChatDB.setRule(messageEntity.getDetaildata().getRule());
                    }else{
//                        singleChatDB.setName(messageEntity.getUser().getUsername());
                        singleChatDB.setCover(chatMessageEntity.getCover());
                    }
                } else {
                    singleChatDB = new SingleChatDB();
                    singleChatDB.setConversationid(messageEntity.getConversationid());
                    singleChatDB.setCover(chatMessageEntity.getCover());
                    singleChatDB.setLastMsgTime(chatMessageEntity.getMsgTime());
                    singleChatDB.setTxuserid(PreferencesStorageUtil.getIMUserName(this));
                    if(!messageEntity.getUser().getUserid().equals(MFPApplication.getInstance().getUser().getId())){
                        singleChatDB.setUnReadMsgCount(1);
                    }

                    if (messageEntity.getOpertype().equals(MyTIMMsgListener.OperType.GROUPMSG)) {
                        singleChatDB.setIsTeam(true);
                        singleChatDB.setName(messageEntity.getDetaildata().getName());
                        singleChatDB.setCover(messageEntity.getDetaildata().getUrl());
                        singleChatDB.setUserCount(messageEntity.getDetaildata().getCount());
                        singleChatDB.setTeamMemberCount(messageEntity.getDetaildata().getCount());
                        singleChatDB.setTeamId(messageEntity.getDetaildata().getId());
                        singleChatDB.setTeamLiveState(messageEntity.getDetaildata().getStatus());
                        singleChatDB.setType(messageEntity.getDetaildata().getType());
                        //TODO 推送消息里面需要区分小组和班级的type
                        singleChatDB.setRule(messageEntity.getDetaildata().getRule());
                    } else {
                        singleChatDB.setName(chatMessageEntity.getUsername());
                        singleChatDB.setIsTeam(false);
                        singleChatDB.setUserId(chatMessageEntity.getUserid());
                        singleChatDB.setTargettype(messageEntity.getUser().getUsertype());
                    }
                }

                //如果是新的聊天消息，添加到聊天列表.不是新的，更新时间

                mSingleChatDBDao.insertOrReplace(singleChatDB);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        TIMManager.getInstance().removeMessageListener(mMyTIMMsgListener);
        TIMManager.getInstance().getUserConfig().setUserStatusListener(null);
        MyTIMMsgListener.removeITIMMsgReceivedCallback(this);
        MFPApplication.getInstance().getEventController().removeUIEventListener(EventDispatcherEnum.UI_EVENT_CHANGE_TAB, this);
    }

    private void showNotification(ChatMessageEntity chatMessageEntity) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setWhen(System.currentTimeMillis())
                .setAutoCancel(true);
        builder.setContentTitle("咨询回复");
        builder.setTicker("你有新消息");
        builder.setContentText("你有新消息");
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 520, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingIntent);
        Notification notification = builder.build();
        notification.defaults |= Notification.DEFAULT_ALL;
        notification.flags |= Notification.FLAG_AUTO_CANCEL;// 点击消息后,该消息自动退出
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(520, notification);
    }

    private boolean shouldInit() {
        ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = getPackageName();
        int myPid = android.os.Process.myPid();
        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }

    private void initIntent(Intent intent) {
//        if (intent != null) {
//            int chooseTab = intent.getIntExtra(Const.MAIN_CHOOSED_TAB, 0);
//            System.out.println("onNewIntent--->" + chooseTab);
//            if (chooseTab == Const.MAIN_TAB_COURSE) {
//                LogUtils.i(TAGS, "onNewIntent--->0" + chooseTab);
////                changeFragment(mMenuList.get(0), intent.getStringExtra(Const.DETAIL_ID));
////                mMainMenuAdapter.setChoosedPosition(1);
//                changeFragment(mMenuList.get(1), intent.getStringExtra(Const.DETAIL_ID));
////                pagerAdapter..(2);
//            } else if (chooseTab == Const.MAIN_TAB_HOMEWORK) {
//                LogUtils.i(TAGS, "onNewIntent--->1" + chooseTab);
//                changeFragment(mMenuList.get(1), intent.getStringExtra(Const.DETAIL_ID));
//                mMainMenuAdapter.setChoosedPosition(2);
//            } else if (chooseTab == Const.MAIN_TAB_MSG) {
//                LogUtils.i(TAGS, "onNewIntent消息--->" + chooseTab);
//                changeFragment(mMenuList.get(10), intent.getStringExtra(Const.DETAIL_ID));
//                mMainMenuAdapter.setChoosedPosition(11);
//            }
//        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        LogUtils.i(TAGS, "onNewIntent(Intent intent)");
        initIntent(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_CHANGE_ORGANIZATION:
                //切换机构
                if (resultCode == Activity.RESULT_OK) {
                    SplashActivity.startActivity(MainActivity.this);
                    MainActivity.this.finish();
                }
                break;
        }
    }

    private void getActivityList() {
        Call<MainActivityListResponse> call = MFPApplication.getInstance().getRestClient().getActivityList();
        call.enqueue(new Callback<MainActivityListResponse>() {
            @Override
            public void onResponse(Call<MainActivityListResponse> call, Response<MainActivityListResponse> response) {
                dismissProgressDialog();
                if (response.body() != null) {
                    if (response.body().getCode() == 200) {
                        if (response.body().getData() != null && response.body().getData().size() > 0) {
                            //TODO 展示弹窗
                            new MainActivityListDialogFragment.MainActivityListDialogBuilder((ArrayList<MainActivityListResponse.MainActivityBean>) response.body().getData())
                                    .build(getSupportFragmentManager().beginTransaction());
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<MainActivityListResponse> call, Throwable t) {
                dismissProgressDialog();
//                finish();
            }
        });
    }

    private String apkDownloadUrl;

    private void checkVersion() {
        //TODO 检查版本
        showProgressDialog();
        Call<CheckVersionResponse> call = MFPApplication.getInstance().getRestClient().checkVersion(MFPApplication.sVersionName);
        call.enqueue(new Callback<CheckVersionResponse>() {
            @Override
            public void onResponse(Call<CheckVersionResponse> call, Response<CheckVersionResponse> response) {
                dismissProgressDialog();
                if (response.body() != null) {
                    if (response.body().getCode() == 200) {
                        if (!"0".equals(response.body().getData().getState())) {
                            apkDownloadUrl = response.body().getData().getVersionurl();
                            newUpDateFragmentDailog(response.body().getData().getContent(), response.body().getData().getState());
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<CheckVersionResponse> call, Throwable t) {
                dismissProgressDialog();
//                finish();
            }
        });
    }

    private void newUpDateFragmentDailog(String msg, final String state) {
        final MUpDateDialogFragment.UpDateDialogBuilder dialog = new MUpDateDialogFragment.UpDateDialogBuilder("是否升级到新版本？", msg);
        dialog.build(getSupportFragmentManager().beginTransaction());
        if ("2".equals(state)) {
            toast("请先完成升级，否则可能无法正常使用", Toast.LENGTH_SHORT);
        }
        dialog.setUpDateCallBack(new MUpDateDialogFragment.UpDateDialogListener() {
            @Override
            public void onSure() {
                if (!"2".equals(state)) {
                    dialog.dismiss();
                }
                downLoadApk();
            }

            @Override
            public void onCancel() {
                dialog.dismiss();
                if ("2".equals(state)) {
                    MainActivity.this.finish();
                }
            }
        });
    }

    private static final int WRITE_EXTERNAL_STORAGE_PERMISSION_REQUESTCODE = 1056;

    /**
     * 启动下载apkService
     */
    private void downLoadApk() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (getPackageManager().checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, getPackageName()) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_STORAGE_PERMISSION_REQUESTCODE);
                return;
            }
        }
        Intent intent = new Intent(MainActivity.this, DownloadApkService.class);
        intent.putExtra("apk_url", apkDownloadUrl);
        startService(intent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case WRITE_EXTERNAL_STORAGE_PERMISSION_REQUESTCODE:
                if (grantResults[0] == 0) {
                    downLoadApk();
                }
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_tab_mine_classroom:
            case R.id.rl_tab_school_online:
            case R.id.rl_tab_class_center:
            case R.id.rl_tab_mine_msg:
            case R.id.rl_tab_main:
                setCurrentPage(v.getId());
                break;
        }
    }

    private void setCurrentPage(int currentTabId) {
        mCurrentTab = currentTabId;
        mTabImgClassCenter.setImageResource(R.mipmap.main_tab_1_normal);
        mTabImgSchoolOnline.setImageResource(R.mipmap.main_tab_2_normal);
        mTabImgMineClassroom.setImageResource(R.mipmap.main_tab_3_normal);
        mTabMineMsg.setImageResource(R.mipmap.main_tab_4_normal);
        switch (currentTabId) {
            case R.id.rl_tab_class_center:
                viewpager.setCurrentItem(0, false);
                mTabImgClassCenter.setImageResource(R.mipmap.main_tab_1_pressed);
                break;
            case R.id.rl_tab_school_online:
                if (TextUtils.isEmpty(PreferencesStorageUtil.getStudentId(MainActivity.this))) {
                    OrganizationActivity.startActivity(MainActivity.this);
                } else {
                    viewpager.setCurrentItem(1, false);
                    mTabImgSchoolOnline.setImageResource(R.mipmap.main_tab_2_pressed);
                }
                break;
            case R.id.rl_tab_main:
                viewpager.setCurrentItem(2, false);
                break;
            case R.id.rl_tab_mine_classroom:
                viewpager.setCurrentItem(3, false);
                mTabImgMineClassroom.setImageResource(R.mipmap.main_tab_3_pressed);
                break;
            case R.id.rl_tab_mine_msg:
                mRedIcon.setVisibility(View.GONE);
                viewpager.setCurrentItem(4, false);
                mTabMineMsg.setImageResource(R.mipmap.main_tab_4_pressed);
                break;
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private boolean isMiuiSystem(Context context) {
        if (!TextUtils.isEmpty(android.os.Build.MANUFACTURER)) {
            if (android.os.Build.MANUFACTURER.equals("Xiaomi")) {
                return true;
            }
        }

        PackageManager packageManager = context.getPackageManager();
        try {
            PackageInfo pkgInfo = packageManager.getPackageInfo("com.miui.cloudservice", 0);
            return (pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public void onMessageChanged(EMMessage emMessage, Object o) {
    }

    @Override
    public void onMessageDelivered(List<EMMessage> list) {
    }

    @Override
    public void onMessageRead(List<EMMessage> list) {
    }

    @Override
    public void onMessageRecalled(List<EMMessage> list) {
    }

    @Override
    public void onMessageReceived(List<EMMessage> list) {
        for (EMMessage message : list) {
            String userid = message.getStringAttribute("userid", "");
            if (!TextUtils.isEmpty(userid) && userid.equals(MFPApplication.getInstance().getUser().getId())) {

            } else {
                EaseUI.getInstance().getNotifier().onNewMsg(message);
            }
//            if(message.)
//
        }
    }

    @Override
    public void onCmdMessageReceived(List<EMMessage> list) {
    }

}